package com.iqik.sc.ns.service.impl;

import com.iqik.sc.dao.TokenDao;
import com.iqik.sc.pojo.Token;
import com.iqik.sc.ns.service.TokenService;
import com.iqik.sc.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private TokenDao tokenDao;

    @Override
    public Token getToken(String email) {
        Token token = new Token();
        token.setEmail(email);
        Optional<Token> result = tokenDao.findOne(Example.of(token));
        return result.isEmpty() ? null : result.get();
    }

    @Override
    public Token createToken(String email) {
        Token token = this.getToken(email);
        if (token == null) {
            Token newToken = new Token();
            newToken.setEmail(email);
            newToken.setToken(TokenUtil.getUUID());
            return tokenDao.saveAndFlush(newToken);
        } else {
            token.setToken(TokenUtil.getUUID());
            return tokenDao.saveAndFlush(token);
        }
    }

    @Override
    public Token getTokenByToken(String token) {
        Token source = new Token();
        source.setToken(token);
        Optional<Token> result = tokenDao.findOne(Example.of(source));
        return result.isEmpty() ? null : result.get();
    }
}
